package com.dxy.netty.tcppackagesolve;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * @Description 演示“tcp拆包-粘包问题”客户端处理器
 * @Author dangxianyue
 * @Date 2023/1/8 17:14
 */
public class TcpNettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        System.out.println("收到服务器消息：" + byteBuf.toString(StandardCharsets.UTF_8));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送10条数据到服务器
        for (int i = 1; i <= 10; i++) {
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello_server_" + i + " ", StandardCharsets.UTF_8);
            ctx.writeAndFlush(byteBuf);
        }
    }
}
